﻿package ua.mihaylenko.cardsplugin.cardsviwer{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
//	import flash.net.
	import flash.text.TextField;
	import ua.mihaylenko.cardsplugin.data.*;
	import ua.mihaylenko.cardsplugin.common.FlashVars;
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.Back;
	import fl.transitions.easing.Elastic;
	import fl.transitions.easing.Strong
	import flash.system.Security;
	import flash.xml.*;
	import ua.mihaylenko.cardsplugin.utils.StringUtil;
	
	public class Card extends MovieClip {
		public var _errorMsg:Sprite;
		public var _smcRight:Sprite;
		public var _smcPreloader:MovieClip;
		private var XMLoader:URLLoader
		private var _smcLoader:Loader;
		private var _bmPreview:Bitmap;
		private var _smcLogo:Sprite;
		private var _twOpenClose:Tween;
		private var _twHideLogo:Tween;
		private var _sImage:String;
		private var _dItem:DataThumb;
		private var _aFilds:Array;
		private var _aImages:Array;
		public var _sSuccesURL:String;
		
		//designer details
		public var _sDesignerProfileUrl:String;
		public var _sDesignerID:String;
		public var _sDesignerName:String;
		public var _sDownload:String;
		public var _sComments:String;
		public var _multipage:Boolean = false;
		
		private var _bLoaded:Boolean;
		public var _sdtDescription:TextField;		
		public static var _nLogoY:Number;		
		public static var _oPictureSettings:Object = { width:330.0, height:322.0, x:7, y:10 };
		public static var _currentW:uint = 300;
		public static var _currentH:uint = 300;
		public static var instance:Card;
		
		// the callback function when loaded is finished
		private var _loadedEvent:Object = null;
		
		public function Card() {
			//_sdtDescription = _smcRight["_sdtDescription"];
			_sdtDescription.mouseEnabled = false;
			_errorMsg.visible = false;
			//_smcRight.scale9Grid = new Rectangle(6, 6, 195, 325);
			instance = this;
		}
		public function onInitialaze(mcLogo:Sprite){
			_smcLogo = mcLogo;
			if(!_nLogoY){
				_nLogoY = _smcLogo.y;
			}
			this.alpha = 0;
			this.visible = false;
		}
		public function get loaded():Boolean{
			return _bLoaded;
		}
		public function get id():String{
			return _dItem.id;
		}
		public function show(dItem:DataThumb){
			_dItem = dItem;
			_bLoaded = false;
			_aFilds = new Array();
			_aImages = new Array();
			this.visible = true;
			this.alpha = 0;			
			Security.allowDomain(FlashVars.getInstance().getData("domain"));
			Security.allowInsecureDomain(FlashVars.getInstance().getData("domain"));
			if(_smcLoader){
				if(_smcLoader.contentLoaderInfo.hasEventListener(ProgressEvent.PROGRESS)){
					_smcLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
					_smcLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
					_smcLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, imageLoaded);
				}
			}
			for(var i:int=0; i<this.numChildren; i++){
				if(this.getChildAt(i) is Bitmap){
					this.removeChildAt(i);
				}
			}
			_smcLoader = null;
			XMLoader = new URLLoader();
			XMLoader.addEventListener(Event.COMPLETE, onLoadDeteils);
			var sURL:String = new String(FlashVars.getInstance().getData("domain") + "/?page=template-xml;TemplateID=" +dItem.id);
			XMLoader.load(new URLRequest(sURL) );
			if(_twOpenClose){
				if(_twOpenClose.hasEventListener(TweenEvent.MOTION_FINISH)){
					_twOpenClose.addEventListener(TweenEvent.MOTION_FINISH, close);
					_twOpenClose.stop();
					_twHideLogo.stop();
				}
			}
			_sImage = null;
			_smcPreloader.visible = true;
			_errorMsg.visible = false;
			_smcPreloader._loaderAnim.gotoAndPlay(2);
			_twOpenClose = new Tween(this, "alpha", Strong.easeInOut, this.alpha, 1, 30);
//			_twHideLogo =  new Tween(_smcLogo, "y", Regular.easeOut, _smcLogo.y, -_smcLogo.height, 20);
			_twHideLogo =  new Tween(_smcLogo, "alpha", Strong.easeInOut, _smcLogo.alpha, 0, 30);
			_twHideLogo.addEventListener(TweenEvent.MOTION_FINISH, hideLogo);
			
		}
		private function hideLogo(oEvent:TweenEvent){
			_twHideLogo.removeEventListener(TweenEvent.MOTION_FINISH, hideLogo);
			_smcLogo.visible = false;
		}
		public function get filds():Array{
			return _aFilds;
		}
		public function get imageUrl():String
		{
			return _sImage;			
		}
		public function get bitmap():Object{
			var bmdReturn:BitmapData = new BitmapData(_bmPreview.bitmapData.width, _bmPreview.bitmapData.height, true, 0x000000);
			bmdReturn.draw(_bmPreview);
			return {source:bmdReturn, x:_bmPreview.x, y:_bmPreview.y, width:_bmPreview.width, height:_bmPreview.height}
		}
		public function get images():Array{
			return _aImages;
		}
		private function onLoadDeteils(oEvent:Event){
			var xXML:XMLDocument = new XMLDocument(oEvent.target.data);
			//trace(xXML);
			_sdtDescription.text = xXML.firstChild.attributes.Comments;
			_sSuccesURL = xXML.firstChild.attributes.AccessURL;
			
			//get designer details
			_sDesignerProfileUrl=xXML.firstChild.attributes.DesignerProfileUrl;
			_sDesignerID=xXML.firstChild.attributes.DesignerID;
			_sDesignerName=xXML.firstChild.attributes.DesignerName;
			_sDownload=xXML.firstChild.attributes.Download;
			_sComments=xXML.firstChild.attributes.Comments;
			
			parseVarsToObject(xXML.firstChild.childNodes);
			_smcLoader = new Loader();
			_smcLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_smcLoader.contentLoaderInfo.addEventListener(Event.INIT, imageLoaded);
			_smcLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			//trace(_sImage);
			//_250x500
			//trace(resizedImageUrl());
			try{
				_smcLoader.load(new URLRequest(resizedImageUrl() ));
			}catch(e:Error){
				//trace("badURL")
			}
		}		
		private function parseVarsToObject(aXML:Array){
//			trace("-------------------");
//			trace(aXML);
//			trace("-------------------");
			for(var i:int = 0; i<aXML.length; i++){
				if(aXML[i].nodeName=="Pages"){
					for(var im:int = 0; im< aXML[i].childNodes.length; im++){
						_sImage = FlashVars.getInstance().getData("domain") + "/" + aXML[i].childNodes[im].attributes.PreviewImage;
						
						// use the first page as preview page
						break;
//						_aImages.push(FlashVars.getInstance().getData("domain") + "/" + aXML[i].childNodes[im].attributes.PreviewImage);
					}
				}
				_multipage = (aXML[i].childNodes.length > 1);
				
				if(aXML[i].nodeName == "Images" && aXML[i].childNodes.length){
					
					for(var nImages:int = 0; nImages<aXML[i].childNodes.length; nImages++){
						var nodeImage:XMLNode = aXML[i].childNodes[nImages];
						var sName:String = nodeImage.attributes.Name;
						//added for color picker(by sharwan)
						var sColourPicker:String = nodeImage.attributes.ColourPicker;
						
						var aStok:Array = new Array();
						for(var nStok:int = 0; nStok<nodeImage.childNodes.length; nStok++){
							aStok.push({name:aStok, value:nodeImage.childNodes[nStok].attributes.FileID, src:nodeImage.childNodes[nStok].attributes.Thumb});
						}
						//colourpicker:sColourPicker, added for colour picker(by sharwan)
						_aImages.push({name: sName, colourpicker:sColourPicker, data: aStok});
					}
				}

				if(aXML[i].nodeName=="Fields"){
					for(var j:int=0; j<aXML[i].childNodes.length; j++){
						var oFild:Object = new Object();
						oFild.fildName = aXML[i].childNodes[j].attributes.FieldName;
						oFild.maxLength = aXML[i].childNodes[j].attributes.MaxLen;
						oFild.hint = aXML[i].childNodes[j].attributes.Hint;
						var valueArr:Array = new Array();
						for (var k:uint = 0; k < aXML[i].childNodes[j].childNodes.length; k++ )
						{
							valueArr.push({label: aXML[i].childNodes[j].childNodes[k].firstChild, data: aXML[i].childNodes[j].childNodes[k].firstChild});
						}
						oFild.values = valueArr;
						if(aXML[i].childNodes[j].attributes.Multiline == "1"){
							oFild.multiline = true;
						}
						_aFilds.push(oFild);
					}
				}
			}
		}
		private function imageLoaded(oEvent:Event){
			_smcLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			_smcLoader.contentLoaderInfo.removeEventListener(Event.INIT, imageLoaded);
			_smcLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_bmPreview = (oEvent.target.content as Bitmap);	
			_bmPreview.smoothing = true;
			var nPercent:Number = _bmPreview.width/_bmPreview.height;
			var nScaleW:Number = _oPictureSettings.width/_bmPreview.width;
			var nScaleH:Number = _oPictureSettings.height/_bmPreview.height;
			if(nScaleW<1 || nScaleH<1){
				if(nScaleW<nScaleH){
					_bmPreview.width *= nScaleW;
					_bmPreview.height = _bmPreview.width / nPercent;
				}else{
					_bmPreview.height *= nScaleH;
					_bmPreview.width = _bmPreview.height * nPercent;
				}
			}
			var nFreeWidth:Number = -(_bmPreview.width - _oPictureSettings.width)/2;
			var nFreeHeight:Number = -(_bmPreview.height - _oPictureSettings.height)/2;
			if(nFreeWidth>0)nFreeWidth = nFreeWidth; else nFreeWidth = _oPictureSettings.x;
			if(nFreeHeight>0)nFreeHeight = nFreeHeight+1;else nFreeHeight = _oPictureSettings.y;
			_bmPreview.x = nFreeWidth;
			_bmPreview.y = nFreeHeight;
			
			this.addChild(_bmPreview);
			_smcPreloader.visible = true;
			_smcPreloader._loaderAnim.gotoAndStop(1);
			_smcPreloader.visible = false;
			_bLoaded = true;
			
			if(this._loadedEvent != null){
			    try{
				    _loadedEvent._function.apply(_loadedEvent._object, [this]);
				}catch(e:Error){}
				this._loadedEvent = null;
			}
		}
		//Hanlder IO error to present a friendly error message
		private function ioErrorHandler(event:Event):void
		{
			_errorMsg.visible = true;
			_smcPreloader._loaderAnim.gotoAndStop(1);
			_smcPreloader.visible = false;
		}
		private function onProgress(oEvent:ProgressEvent){
			var _nPercentLoaded:int = int(Math.floor(oEvent.bytesLoaded/oEvent.bytesTotal) * 100 );
			_smcPreloader.gotoAndStop(_nPercentLoaded);
		}
		public function hide(){
			if(_twOpenClose){
				if(_twOpenClose.hasEventListener(TweenEvent.MOTION_FINISH)){
					_twOpenClose.addEventListener(TweenEvent.MOTION_FINISH, close);
					_twOpenClose.stop();
					_twHideLogo.stop();
				}
				if(_twHideLogo.hasEventListener(TweenEvent.MOTION_FINISH)){
					_twHideLogo.removeEventListener(TweenEvent.MOTION_FINISH, hideLogo);
				}
			}
			_smcLogo.visible = true;
			_twOpenClose = new Tween(this, "alpha", Strong.easeInOut, this.alpha, 0.0, 30);
			_twHideLogo =  new Tween(_smcLogo, "alpha", Strong.easeInOut, _smcLogo.alpha, 1, 30);
//			_twHideLogo =  new Tween(_smcLogo, "y", Regular.easeIn, _smcLogo.y, _nLogoY, 20);
			if(XMLoader.hasEventListener(Event.COMPLETE)){
				XMLoader.removeEventListener(Event.COMPLETE, onLoadDeteils);
			}
			if(_smcLoader){
				if(_smcLoader.contentLoaderInfo.hasEventListener(ProgressEvent.PROGRESS)){
					_smcLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
					_smcLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
					_smcLoader.contentLoaderInfo.removeEventListener(Event.INIT, imageLoaded);
				}
			}
			_twOpenClose.addEventListener(TweenEvent.MOTION_FINISH, close);
		}
		private function close(oEvent:TweenEvent){
			_twOpenClose.stop();
			_twHideLogo.stop();
			_twOpenClose.removeEventListener(TweenEvent.MOTION_FINISH, close);
			this.visible = false;
			_twOpenClose = null;
			_twHideLogo = null;
		}
		
		public function resize(width:int, height:int):void
		{
			_smcRight.x = width - _smcRight.width;
			_smcRight.height = height - 68;
			_smcPreloader.x = (width - _smcRight.width) / 2;
			_smcPreloader.y = _smcRight.height / 2;
			_errorMsg.x = (width - _smcRight.width) / 2;
			_errorMsg.y = _smcRight.height / 2;
			_sdtDescription.x = _smcRight.x + 8;
			_sdtDescription.height = _smcRight.height - 14;
			_oPictureSettings.width = width - _smcRight.width;
			_oPictureSettings.height = _smcRight.height-30;
			calculateWH();
		}
		
		public function calculateWH():Boolean
		{
			var tempW:uint = Math.max(Math.floor(_oPictureSettings.width / 50), 1) * 50;
			var tempH:uint = Math.max(Math.floor(_oPictureSettings.height / 50), 1) * 50;
			if ( (tempW == _currentW) && (tempH == _currentH) )
			{
				return false;
			}
			_currentW = tempW;
			_currentH = tempH;
			if (_bLoaded && this.visible) 
			{
				this.removeChild(_bmPreview);
				_smcLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
				_smcLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				_smcLoader.contentLoaderInfo.addEventListener(Event.INIT, imageLoaded);
				//trace(_sImage);
				//_250x500
				//trace(resizedImageUrl());
				try{
					_smcLoader.load(new URLRequest(resizedImageUrl()));
				}catch(e:Error){
					//trace("badURL")
				}
			}
			
			return true;
			//trace("_currentW" + _currentW);
			//trace("_currentH" + _currentH);
		}
		private function resizedImageUrl():String
		{			
			return StringUtil.replace(_sImage, ".jpg", "_"+_currentW.toString()+"x"+_currentH.toString()+".jpg");
		}
		public function removeImage():void		
		{
			try{
			if (_bmPreview && (this.getChildIndex(_bmPreview) >= 0)) this.removeChild(_bmPreview);
			}catch (e:Error)
			{
				//
			}
		}
		
		// set the callback function when loading finishes
		public function setLoadedListener(_loaded:Object):void{
		    this._loadedEvent = _loaded;
		}
	}	
}